<?php
class Delivery_Model_DbTable_Tags
	extends Delivery_Model_DbTable_Abstract

{
	protected $_name = 'tags';
	protected $_primary = 'idTag';
	
	public function getById( $idTaga ){
		
		return 
			$this->_db->fetchRow(
				$this->select()->where('idTag = ?', $idTaga, Zend_Db::INT_TYPE)
			);
	}
	
	public function getByName( $name ){
		
		
		return 
			$this->_db->fetchRow(
				$this->select()->where('nombre = ?', $name)
			);
	}
	
	
	public function getAll(){
					
		return 
			$this->_db->fetchAssoc(
				$this->select()					
			);
	}
	
	public function getByType( $idTagType )
	{
		$select = $this->select()->from($this->_name)
					->setIntegrityCheck(false)
					->joinUsing('tags_tipo', 'idTagType', array())
					->where('idTagType = ?', $idTagType, Zend_Db::INT_TYPE);
	
		return $this->_db->fetchAll( $select ); 
	}
	
	public function getByTypeAndName( $tagType, $tagName )
	{
		$select = $this->select()->from($this->_name)
					->setIntegrityCheck(false)
					->joinUsing('tags_type', 'idTagType', array())
					->where('tags.nombre = ?', $tagName)
					->where('tags_type.nombre = ?', $tagType);
	
		return $this->_db->fetchRow( $select ); 
	}
	
	public  function getLinked( $idCiudad = null )
	{
	    $select = $this->select( self::SELECT_WITH_FROM_PART )
            ->columns(array('cantidad'=>'COUNT(1)'))
            ->joinUsing('tags_negocio', 'idTag', array())
            ->join('negocios', 'negocios.idNegocio = tags_negocio.idNegocio AND activo = 1', array())
            ->where('idTagType < 6')
            ->group('idTag')
            ->order( "FIND_IN_SET(idTagType, '3,1,2,4') , nombre ");
	    
	    if( $idCiudad ){
	        $select
	            ->join('direcciones', 'direcciones.idDireccion = negocios.idDireccion ', array())
	            ->where('idCiudad = ?', $idCiudad, Zend_Db::INT_TYPE);
		}    
        
//		$sql = "
//			SELECT t.*, count(1) AS cantidad
//			FROM tags_negocio tn 
//			JOIN tags t using (idTag)
//			JOIN negocios n ON n.idNegocio = tn.idNegocio AND activo = 1
//			WHERE idTagType < 6
//		";
		
		
		
//		$sql.= "
//			GROUP BY idTag
//			ORDER BY FIND_IN_SET(idTagType, '3,1,2,4') , nombre
//		";
		
		return $this->_db->fetchAll( $select );
	}
}